package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"path/filepath"
	"time"
	"zk1/api/handler/request"
	"zk1/srv/pkg"
	__ "zk1/srv/proto"
)

func Login(c *gin.Context) {
	var data request.Login
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  "错误",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:8002", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	userLogin := __.NewUserServerClient(conn)
	userLogin.Login(c, &__.UserLoginReq{Name: data.UserName, Password: data.Password})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": "ok",
	})
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	name := filepath.Ext(file.Filename)
	if name != ".mp4" && name != ".mov" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  "文件不对",
			"data": nil,
		})
		return
	}
	if file.Size >= 20*1024*1024*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  "内容过大",
			"data": nil,
		})
		return
	}
	names := time.Now().Format("20060102150405") + name
	dst := "D:\\gocode\\src\\gao4\\3\\rk\\27\\zk1\\srv\\stonic\\upload\\" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)
	pkg.Oss(names, dst)
	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
}
